package com.nba.system.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.nba.common.utils.ResponseUtils;
import com.nba.common.controller.BaseController;
import com.nba.common.exception.CustomException;
import com.nba.common.form.RequestDataForm;
import com.nba.common.form.ResponseDataForm;
import com.nba.common.service.IService;
import com.nba.common.utils.DateUtil;
import com.nba.common.utils.Environment;
import com.nba.common.utils.FileUtils;
import com.nba.common.utils.MapUtils;
import com.nba.common.utils.PropertiesLoaderUtil;
import com.nba.common.utils.UserSessionBean;

/**
 * @author Jesse 用户URL统一入口
 */
@Controller
@RequestMapping("/topic")
public class TopicController extends BaseController{
	private final String EXEC_SERVICE = "execService";
	private final String AJAX_SERVICE = "ajaxService";
	private final String QUERY_SERVICE = "queryService";
	/**
	 * 跳转页面
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{id}")
	public String topic(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) throws CustomException,Exception {
		RequestDataForm requestDataForm = this.getRequestDataForm(id, request, response);
		Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
		String title = MapUtils.getString(urlSqlMap, "TITLE");
		String addOL = MapUtils.getString(urlSqlMap, "ADD_OPERATE_LOG");
		//保存操作日志
		if("1".equals(addOL))
		    this.addOperateLog(request, id, title);
		
		return MapUtils.getString(urlSqlMap, "PAGE");
	}
	
	/*@RequestMapping(value = "/uploadImg/{id}")
	public @ResponseBody Object uploadImg(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RequestDataForm requestDataForm = getRequestDataForm(id, request, response);
		Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
		String service = MapUtils.getString(urlSqlMap, "SERVICE_NAME");
		if (null == service || "".equals(service)) {// service为空，直接跳转到页面
			return MapUtils.getString(urlSqlMap, "PAGE");
		} else {
			request.setAttribute(Environment.URL_SQL_MAP, urlSqlMap);// add
			WebApplicationContext ctx = WebApplicationContextUtils
					.getWebApplicationContext(request.getSession()
							.getServletContext());
			ResponseDataForm responseDataForm = ((IService) ctx
					.getBean(service)).service(requestDataForm);
			
			request.setAttribute("responseDataForm", responseDataForm);
			String fileid =  jdbcDao.queryForString("select max(att_id) lastId from sys_attachment_tab", null);
			Map<String, Object> m = new HashMap<String, Object>();
			m.put("error", 0);
			m.put("message", "上传成功");
			m.put("url", request.getContextPath() + "/topic/getFile/" + fileid);
			return m;
		}
	}	*/
	/**
	 * 返回json格式数据,返回类型可以是string，map，list，请将xmlresultType设置成正确的格式
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ajax/{id}")
	public @ResponseBody
	Object ajax(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RequestDataForm requestDataForm = getRequestDataForm(id, request, response);
		WebApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		return ((IService) ctx.getBean(this.AJAX_SERVICE)).service(requestDataForm)
				.getAjaxObject();
		
	}

	@RequestMapping(value = "/exec/{id}")
	public @ResponseBody
	Object exec(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			RequestDataForm requestDataForm = getRequestDataForm(id, request, response);
			Map<String, Object> returnMap = new HashMap<String, Object>();
		    //保存操作日志
            Map<String, Object> urlSqlMap = requestDataForm.getUrlSqlMap();
            this.addOperateLog(request, id, MapUtils.getString(urlSqlMap, "TITLE"));
            //
			WebApplicationContext ctx = WebApplicationContextUtils
					.getWebApplicationContext(request.getSession()
							.getServletContext());
			ResponseDataForm responseDataForm = ((IService) ctx
					.getBean(this.EXEC_SERVICE)).service(requestDataForm);
			returnMap.put("success", true);
			returnMap.put("result", responseDataForm.getResult());
			returnMap.put("resultInfo", responseDataForm.getResultInfo());
			if (ResponseDataForm.FAULAIE == responseDataForm.getResult()) {// 异常信息
				returnMap.put("validate", responseDataForm.getErrorList());
			}
			return returnMap;
		} catch (Exception e) {
			e.printStackTrace();
			final String message = e.getMessage();
			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					put("success", false);
					put("result", "3");
					put("resultInfo", message);
				}
			};
		}
	}

	/**
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list/{id}")
	public @ResponseBody
	Object list(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RequestDataForm requestDataForm = getRequestDataForm(id, request, response);
		
		WebApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(request.getSession()
						.getServletContext());
		ResponseDataForm responseDataForm = ((IService) ctx
				.getBean(this.QUERY_SERVICE)).service(requestDataForm);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", responseDataForm.getPaginForm().getTotalCount());
		map.put("rows", responseDataForm.getPaginForm().getDataList());
		return map;
		//try {
		/*} catch (Exception e) {
			e.printStackTrace();
			final String message = e.getMessage();
			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					put("success", false);
					put("result", "3");
					put("resultInfo", message);
				}
			};
		}
		return null;*/
	}

	/**
	 * 加载单条数据，返回json字符串,请使用ajaxservice,请将xml的resultType设置成map
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/load/{id}")
	public @ResponseBody
	Object load(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		RequestDataForm requestDataForm = getRequestDataForm(id, request, response);
		String service = "ajaxService";
		try {
			WebApplicationContext ctx = WebApplicationContextUtils
					.getWebApplicationContext(request.getSession()
							.getServletContext());
			ResponseDataForm responseDataForm = ((IService) ctx
					.getBean(service)).service(requestDataForm);
			
			Map obj = new HashMap();
			obj.put("success", true);
			obj.put("root", responseDataForm.getAjaxObject());
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			final String message = e.getMessage();
			return new HashMap<String, Object>() {
				private static final long serialVersionUID = 1L;
				{
					put("success", false);
					put("resultInfo", message);
				}
			};
		}
	}
	
	
	
	
	@RequestMapping(value = "/getFile/{id}")
	public void getFile(@PathVariable String id,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		Map<String, Object> urlSqlMap = jdbcDao.queryForMap(
				"select name, path, size, ext from accessory_file where id = ?",
				new Object[] { id });
		if (urlSqlMap == null || urlSqlMap.size() == 0) {
			throw new CustomException(-1,
					"附件不存在!.");
		}
		String basePath = PropertiesLoaderUtil.getPropValue("pic.base.path");
		String path = basePath + urlSqlMap.get("path").toString();
		String filename = urlSqlMap.get("name").toString();
		File file = new File(path);
        // 取得文件名。
        // 取得文件的后缀名。

        // 以流的形式下载文件。
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.setContentType("appliation/octet-stream"); 
        if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
            filename = URLEncoder.encode(filename, "UTF-8");  //针对IE
        } else {  
            filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");  //针对IE之外的浏览器
        }
//     response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes(Environment.ENCODING), "ISO-8859-1"));
        response.setHeader("Content-disposition", "attachment; filename=" + filename);
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
	}
	
	
	
	
}
